package com.test.moudle.sys.service;

import com.test.R;
import com.test.moudle.sys.entity.User;
import com.test.moudle.sys.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.Permission;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Service
public class UserService {

    @Resource
    private UserRepository userRepository;

    public R create(User user) {

        // 先保存用户
        try {
            user = userRepository.save(user);
        } catch (Exception e) {
            log.error("创建用户失败");
            e.printStackTrace();
            return R.error(e.getMessage());
        }

        return R.ok("创建成功").put("data", user);
    }

    public R findAll(int page, int size) {
        return R.ok().put("data", userRepository.findAll(PageRequest.of(page, size, Sort.by("id"))));
    }

    public User findByName(String name) {
        return userRepository.findByName(name);
    }

    public User findById(Integer id) {
        return userRepository.findById(id).get();
    }

    public Set<Permission> findPermissions(Integer userId) {
        return findById(userId).getPermissionsAll();
    }

    public R update(User user) {
        user = userRepository.save(user);
        return R.ok("创建成功").put("data", user);
    }

    public R delete(Integer id) {
        userRepository.deleteById(id);
        return R.ok("删除成功");
    }

    public User currentUser() {
        return (User) SecurityUtils.getSubject().getPrincipal();
    }
}
